package com.docjohnson.pamphlet.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;

import com.docjohnson.pamphlet.utils.Constants;
import com.docjohnson.pamphlet.utils.Utils;

public class Client implements Constants {

    public static String getResponse(final Activity activity, final HttpUriRequest request, final int successCode, final boolean requiresResponse) {
        final StringBuilder sb = new StringBuilder();

        final HttpClient client = getHttpClient();
        try {
            final HttpResponse response = client.execute(request);
            final HttpEntity entity = response.getEntity();


            if (entity != null) {
                final InputStream stream = entity.getContent();
                byte bytes[] = new byte[4096];
                int numBytes;
                while ((numBytes = stream.read(bytes)) != -1) {
                    if (numBytes != 0) {
                        sb.append(new String(bytes, 0, numBytes));
                    }
                }
            }

            if (response.getStatusLine().getStatusCode() != successCode) {
                closeConnection(client);
                throw new Exception(sb.toString());
            }
            closeConnection(client);
            if (!requiresResponse) return null;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static File getFileResponse(final Activity activity, final HttpUriRequest request, final int successCode, final boolean requiresResponse, int id, String exension) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pamplets/" + id + "." + exension);

        if (!Utils.isConnectedOrConnecting(activity)) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setMessage("No Internet Connection")
                            .setCancelable(false)
                            .setTitle("message")
                            .setPositiveButton("retry", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    getResponse(activity, request, successCode, requiresResponse);
                                }
                            })
                            .setNeutralButton("Settings", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    activity.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();

                }
            });
            return null;
        }


        final HttpClient client = getHttpClient();
        try {
            final HttpResponse response = client.execute(request);
            final HttpEntity entity = response.getEntity();


            if (entity != null) {
                final InputStream stream = entity.getContent();
                byte bytes[] = new byte[4096];
                OutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;
                while ((len = stream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

            }

            if (response.getStatusLine().getStatusCode() != successCode) {
                closeConnection(client);
                throw new Exception();
            }
            closeConnection(client);
            if (!requiresResponse) return null;

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return file;
    }

    private static void closeConnection(final HttpClient client) {
        try {
            final Method closeMethod = client.getClass().getMethod("close");
            if (closeMethod != null) {
                closeMethod.invoke(client);
            }
        } catch (IllegalArgumentException ignored) {
        } catch (IllegalAccessException ignored) {
        } catch (InvocationTargetException ignored) {
        } catch (SecurityException ignored) {
        } catch (NoSuchMethodException ignored) {
        }
    }

    private static HttpClient getHttpClient() {
        Class<?> androidClientClass;
        try {
        	
            androidClientClass = Class.forName("android.net.http.DefaultHttpClient");
            final Method method = androidClientClass.getMethod("newInstance", String.class);

            return (HttpClient) method.invoke(null, "newInstance");

        } catch (ClassNotFoundException ignored) {
        } catch (IllegalArgumentException ignored) {
        } catch (IllegalAccessException ignored) {
        } catch (InvocationTargetException ignored) {
        } catch (SecurityException ignored) {
        } catch (NoSuchMethodException ignored) {
        }

        return new DefaultHttpClient();
    }

    private static String notInitialized() {
        return "{ \"errorCode\" : 101 }";
    }

    public static String getDatafromServer(final Activity activity) {

        final HttpPost post = new HttpPost();
        post.setHeader("test", "1");

        final List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("test", "1"));
        try {
            post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return getResponse(activity, post, 200, true);

    }

    public static String needUpdateApplicationData(final Activity activity, final String appUpdateVersion) {
        final HttpPost post = new HttpPost(SERVER_URL);
        final List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("appUpdateVersion", appUpdateVersion));
        try {
            post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return getResponse(activity, post, 200, true);
    }

    public static String getPamphlet(final Activity activity, final String pamphletId) {

        final HttpGet post = new HttpGet(SERVER_URL);

        return getResponse(activity, post, 200, true);

    }

    public static String getProduct(final Activity activity, final String productId) {

        final HttpGet post = new HttpGet(SERVER_URL + "?favId=" + productId);
        post.setHeader("favId", productId);

        return getResponse(activity, post, 200, true);
    }
}
